var table;
$(function () {
    getQuestionConf();
    table = $("#question").DataTable({
        "ajax": {
            url:"../../admin/question",
            type:"GET",
            // success:function (data) {
            //     console.log(data);
            // },
            error:function(XMLHttpRequest,textStatus,errorThrown){
                console.log(data);
                console.log("载入数据出错");
            }
        },
        "scrollX": 1300,
        "bProcessing": true,
        "bServerSide": true,
        "bPaginate": true,
        "bAutoWidth": false,
        "bInfo": true,//页脚信息
        "bFilter": false,//禁用搜索
        "bSort":false,//禁用排序
        "aLengthMenu": [10,20,30],
        "sPaginationType":'full_numbers',
        "columns": [
            {"data":"id","width": "30"},
            {"data":"question"},
            { "data": "answer" ,"width": "30"},
            { "data":"a_option"},
            { "data":"b_option"},
            { "data":"c_option"},
            { "data":"d_option"},
            { "data":"e_option"},
            { "data":"f_option"},
            { "data":"g_option"},
            { "data":"h_option"}
        ],
        "aoColumnDefs": [

        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex) {
            $("td:first", nRow).html(iDisplayIndex + 1);
            return nRow;
        },
        "oLanguage": {
            "sProcessing": "处理中...",
            "sLengthMenu": "每页 _MENU_ 条",
            "sZeroRecords": "没有匹配结果",
            "sInfo": " _START_ 至 _END_ 项结果，共 _TOTAL_ 项",//显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项
            "sInfoEmpty": "",//显示第 0 至 0 项结果，共 0 项
            "sInfoFiltered": "",//(由 _MAX_ 项结果过滤)
            "sInfoPostFix": "",
            "sSearch": "搜索：",
            "sUrl": "",
            "sEmptyTable": "没有数据呀!",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            }
        }
    });
    importQuesConfig($);
})
new SMValidator('#questionFrom');

function getQuestionConf() {
    $.ajax({
        url: "../../admin/question/questionConf",
        type: "GET",
        dataType: "json",
        beforeSend: function () {
        },
        success: function (data) {
            if(data){
                $("#id").val(data.id)
                $("#question_num").val(data.question_num)
                $("#question_time").val(data.question_time)
                $("#question_type").val(data.question_type)
                $("#question_pass").val(data.question_pass)
            }else {
                console.log(data)
            }
        }, error: function () {
        }
    });
}
function question_confirm(){
    if(SMValidator.validate('#questionFrom')){
        $.ajax({
            url: "../../admin/question",
            type: "POST",
            dataType: "json",
            data: $("#questionFrom").serialize(),
            beforeSend: function () {
            },
            success: function (data) {
                if(data){
                    console.log(data)
                    var msg = ""
                    if(data == -2){
                        msg = "选题太多"
                        Lobibox.notify('error', {
                            msg: msg,
                            sound: false
                        })
                    }else if(data == -1){
                        msg = "删除失败"
                        Lobibox.notify('error', {
                            msg: msg,
                            sound: false
                        })
                    }else{
                        msg = "修改成功"
                        Lobibox.notify('success', {
                            msg: msg,
                            sound: false
                        })
                    }
                }else {
                    console.log(data)
                }
            }, error: function () {
            }
        });
    }
}
function import_question() {
    $("#question-modal-form").modal("show");
}

function importQuesConfig($) {
    $("#importQuesFile").ace_file_input({
        no_file:'选择文件 ...',
        btn_choose:'选择',
        btn_change:'选择',
        droppable:false,
        thumbnail:false, //| true | large
        whitelist:'xlsx|xls'
    }).on('change', function(){
        var names=$(this).data('ace_input_files')[0].name.split(".")
        if(names[names.length-1]!=="xlsx"&&names[names.length-1]!=="xls"){
            alert("只接受xlsx或xls文件");
            return true;
        }
    });
}

function submitQuestionFile() {
    $("#questionFileForm").ajaxSubmit({
        type: 'POST',
        dataType: "json",
        url:"../../admin/question/import",
        success: function(data){
            if(data){
                Lobibox.notify('success', {
                    msg: "导入成功",
                    sound: false
                });
                table.draw();
            }else {
                Lobibox.notify('error', {
                    msg: "导入失败",
                    sound: false
                });
            }
            $("#question-modal-form").modal("hide")
        },
        error: function(XmlHttpRequest, textStatus, errorThrown){
            alert( "error");
        }
    })
}

function output_question(){
    window.location.href="../../admin/question/exportEmail.html";
}

//限制框内只能填数字
$("#questionFrom").find("input").each(function () {
    $(this).bind('keyup',function(){this.value = this.value.match(/^[+-]?\d*\.?\d*$/) ? this.value : checkDecimal(this.value);});
    $(this).bind('blur',function(){this.value = this.value.match(/^[\-]?\d*?\.?\d*$/) ? this.value : checkDecimal(this.value);});
})

function checkDecimal(value){
    var newValue = value[0];
    var returnValue = "";
    for (var i =1; i <= value.length; i++) {
        if(!newValue.match(/^[\-]?\d*?\.?\d*$/)){
            break;
        }
        returnValue = newValue;
        newValue += value[i];
    }
    return returnValue;
}

